package com.ggbz.controller;


import com.ggbz.common.utils.JwtUtil;
import com.ggbz.common.utils.Result;
import com.ggbz.entity.Students;
import com.ggbz.entity.dto.StudentUpdateRequest;
import com.ggbz.service.StudentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLOutput;

/**
 * <p>
 * 学生信息表，存储学生的详细信息 前端控制器
 * </p>
 *
 * @author ggbz
 * @since 2025-03-08
 */
@RestController
@RequestMapping("/students")
public class StudentsController {
    @Autowired
    private StudentsService studentsService;

    @GetMapping()
    public Result getStudentById(@RequestHeader("Authorization") String token) {
        String userId = (String) JwtUtil.getTokenBody(token).get("userId");
        Students student = studentsService.getStudentById(Long.valueOf(userId));
        try {

            return Result.ok()
                    .data("student", student);
        } catch (RuntimeException e) {
            return Result.error()
                    .code(404)
                    .message(e.getMessage());
        }
    }

    @PutMapping()
    public Result updateStudent(
            @RequestHeader("Authorization") String token,
            @RequestBody StudentUpdateRequest request) {
        try {
            String userId = (String) JwtUtil.getTokenBody(token).get("userId");
            studentsService.updateStudent(Long.valueOf(userId), request);
            return Result.ok()
                    .message("学生信息更新成功");
        } catch (RuntimeException e) {
            return Result.error()
                    .code(e.getMessage().contains("不存在") ? 404 : 500)
                    .message(e.getMessage());
        }
    }
}

